<template>
  <div>

    <van-nav-bar
      title="登录"
    />
    <!-- submit事件只有表单校验通过了才能触发 -->
    <van-form @submit="login">
      <van-field
        v-model="mobile"
        required
        label="手机号"
        placeholder="请输入手机号"
        :rules="rules.mobile"
      />
      <van-field
        v-model="code"
        required
        label="验证码"
        placeholder="请输入验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px;">
        <van-button :loading="isDisabled" :disabled="isDisabled" round block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>

</template>

<script>
import { login } from '@/api/user'
export default {
  data() {
    return {
      mobile: '13912345678',
      code: '246810',
      rules: {
        mobile: [
          { required: true, message: '请填写用户名', pattern: /^((13[0-9])|(17[0-1,6-8])|(15[^4,\\D])|(18[0-9]))\d{8}$/ }
        ],
        code: [
          { required: true, message: '请填写验证码', pattern: /^\d{6}$/ }
        ]

      },
      isDisabled: false
    }
  },
  // 需求：优化提交按钮，避免用户重复点击按钮
  // 1。点击之后禁用按钮，
  // 2.发送完请求之后 改为true

  methods: {
    async login() {
      this.isDisabled = true
      try {
        const res = await login(this.mobile, this.code)
        this.$store.commit('user/setToken', res.data)
        if (this.$route.query.goBack) {
          this.$router.back()
          return
        }
        this.$toast.success('登录成功')
        const back = this.$route.query.back || '/'
        this.$router.push(back)
      } catch {
        this.$toast.success('登录失败')
      }
      this.isDisabled = false
    }
  }

}
</script>

<style>

</style>
